﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Net;
namespace Common
{
     public class TimeoutStream : Stream
    {
        #region Public

        public TimeoutStream(Stream stream, int timeoutMillis)
        {
            _stream = stream;
            _endTime = DateTime.Now.Add(new TimeSpan(0, 0, 0, 0, timeoutMillis));
        }

        public override bool CanRead
        {
            get { return _stream.CanRead; }
        }

        public override bool CanSeek
        {
            get { return _stream.CanSeek; }
        }

        public override bool CanWrite
        {
            get { return _stream.CanWrite; }
        }

        public override long Length
        {
            get { return _stream.Length; }
        }

        public override long Position
        {
            get { return _stream.Position; }
            set { _stream.Position = value; }
        }

        public override void Flush()
        {
            _stream.Flush();
        }

        public override long Seek(long offset, SeekOrigin origin)
        {
            CheckTimeout();
            return _stream.Seek(offset, origin);
        }

        public override void SetLength(long value)
        {
            _stream.SetLength(value);
        }

        public override int Read(byte[] buffer, int offset, int count)
        {
            CheckTimeout();
            return _stream.Read(buffer, offset, count);
        }

        public override void Write(byte[] buffer, int offset, int count)
        {
            CheckTimeout();
            Write(buffer, offset, count);
        }

        #endregion Public

        #region Private

        private void CheckTimeout()
        {
            if (DateTime.Now.CompareTo(_endTime) > 0)
                throw new WebException("Timeout elapsed waiting for read", WebExceptionStatus.Timeout);
        }

        private readonly Stream _stream;
        private readonly DateTime _endTime;

        #endregion
    }
}

